package com.shopoo.authorization.app.user;

import com.shopoo.api.IUserService;
import com.shopoo.authorization.domain.repository.IUserRepository;
import com.shopoo.dto.SingleResponse;
import com.shopoo.dto.clientobject.TokenCO;
import com.shopoo.dto.cqe.PasswordLoginCmd;
import com.shopoo.exception.Assert;
import com.shopoo.exception.BizException;
import com.shopoo.exception.SysException;
import jakarta.annotation.Resource;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenClaimsSet;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.stereotype.Service;

/**
 *
 * @Author <a href="mailto:android_li@sina.cn">MaoYuan.Li</a>
 * @Date 2023/2/26 22:03
 */
@Service
public class UserServiceImpl implements IUserService {

	@Resource
	private IUserRepository iUserRepository;

	@Resource
	private PasswordEncoder passwordEncoder;
//
//	@Resource
//	private OAuth2TokenGenerator oAuth2TokenGenerator;

	@Override
	public SingleResponse<TokenCO> login(PasswordLoginCmd passwordLoginCmd) {
		UserDetails userDetails = iUserRepository.loadUserByUsername(passwordLoginCmd.getUsername());
		if(!passwordEncoder.matches(passwordLoginCmd.getPassword(), userDetails.getPassword())){
			throw new BizException("密码不正确");
		}
		if(!userDetails.isEnabled()){
			throw new BizException("帐号已被禁用");
		}
		UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
		SecurityContextHolder.getContext().setAuthentication(authentication);
//		token = jwtTokenUtil.generateToken(userDetails);

//		oAuth2TokenGenerator.generate()
//		OAuth2TokenClaimsSet accessTokenClaimsSet = claimsBuilder.build();
//
//		OAuth2AccessToken accessToken = new OAuth2AccessTokenClaims(OAuth2AccessToken.TokenType.BEARER,
//				this.accessTokenGenerator.generateKey(), accessTokenClaimsSet.getIssuedAt(),
//				accessTokenClaimsSet.getExpiresAt(),
//				context.getAuthorizedScopes(), accessTokenClaimsSet.getClaims());
		return null;
	}
}
